package com.ivan.toolkit.common;

import java.net.InetAddress;
import java.util.regex.Pattern;

public class AtString {
	
	public static AtString at(String value) {
		return new AtString(value);
	}
		
	String value;

	public AtString(String value) {
		super();
		this.value = value;
	}

	public AtString _notNull(String exceptionText) {
		if(value == null)
			throw new RuntimeException(exceptionText);
		return this;
	}
	
	public AtString _notEmpty(String exceptionText) {
		if(value == null || value.isEmpty())
			throw new RuntimeException(exceptionText);
		return this;
	}
	
	public AtString _max(int max, String exceptionText) {
		if(value.length() > max)
			throw new RuntimeException(exceptionText);
		return this;
	}
	
	public AtString _min(int min, String exceptionText) {
		if(value.length() < min)
			throw new RuntimeException(exceptionText);
		return this;
	}
	
	public AtString _range(int min, int max, String exceptionText) {
		if(value.length() < min)
			throw new RuntimeException(exceptionText);
		return this;
	}
	
	public AtString _ip(String exceptionText) {
		
		return this._pattern("^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]"
                + "|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$", exceptionText);
	}
	
	public AtString _username(String exceptionText) {
		
		// 数字、26个英文字母或者下划线组成
        return this._pattern("^\\w+$", exceptionText);
	}
	
	public AtString _pattern(String patternString, String exceptionText) {
        Pattern pattern = Pattern.compile(patternString);
		if(!pattern.matcher(value).matches())
			throw new RuntimeException(exceptionText);
		return this;
	}
	
	public String toText() {
		return value;
	}
	
	public long toLong() {
		return Long.parseLong(value);
	}
	
	public int toInteger() {
		return Integer.parseInt(value);
	}
	
	public int toIntegerHex() {
		return toInteger(10);
	}
	
	public int toInteger( int radix) {
		return Integer.parseInt(value, radix);
	}
	
	public InetAddress toInetAddress() {
		try {
			return InetAddress.getByName(value);
		} catch(Exception e) {
			return null;
		}
	}
	
}
